from rest_framework import serializers
from rest_framework.validators import UniqueTogetherValidator

from .models import Problem, Answer, Tag, Comment
from utils.default_hash import BaseHashId


class CommentSerializer(serializers.ModelSerializer):
    add_time = serializers.DateTimeField(read_only=True, format='%Y-%m-%d %H:%M')

    class Meta:
        model = Comment
        fields = '__all__'


class ProblemDetailSerializer(serializers.ModelSerializer):
    class Meta:
        model = Problem
        fields = "__all__"


class ProblemSerializer(serializers.ModelSerializer):
    user = serializers.HiddenField(default=serializers.CurrentUserDefault())
    problem_hash = serializers.HiddenField(default=BaseHashId(id_name='problem_hash', hash_field='title'))

    class Meta:
        model = Problem
        fields = ('user', 'problem_hash', 'title', 'brief', 'detail')


class AnswerDetailSerializer(serializers.ModelSerializer):
    # problem = ProblemDetailSerializer()
    comment = CommentSerializer(many=True)

    class Meta:
        model = Answer
        # fields = ['problem', 'comment']
        fields = '__all__'


class AnswerSerializer(serializers.ModelSerializer):
    user = serializers.HiddenField(default=serializers.CurrentUserDefault())
    answer_hash = serializers.HiddenField(default=BaseHashId(id_name='answer_hash', hash_field='content'))

    # answer_hash = serializers.CreateOnlyDefault(default=serializers.CreateOnlyDefault(getmd5(content)))
    # 这种方法我适用于不用传参数的函数调用

    class Meta:
        model = Answer
        fields = ('user', 'problem', 'content', 'answer_hash')


class TagSerializer(serializers.ModelSerializer):
    tag_hash = serializers.HiddenField(default=BaseHashId(id_name='tag_hash', hash_field='name'))
    user = serializers.HiddenField(default=serializers.CurrentUserDefault())
    add_time = serializers.DateTimeField(read_only=True, format='%Y-%m-%d %H:%M')

    class Meta:
        model = Tag
        fields = '__all__'
        validators = [
            UniqueTogetherValidator(
                queryset=Tag.objects.all(),
                fields=('tag_hash', 'name'),
                message='该标签已存在',
            )]


class TagDetailSerializer(serializers.ModelSerializer):
    pass
